package com.vimi8.chick.plugins.utils

import android.Manifest
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import android.widget.Toast
import com.eros.framework.manager.ManagerFactory
import com.eros.framework.manager.impl.ModalManager
import com.eros.framework.manager.impl.PermissionManager
import com.vimi8.chick.plugins.constant.Constant.PermissionConstants.REQUEST_CODE_APP_INSTALL
import com.vimi8.chick.plugins.model.DownloadServiceListener

object ServiceUtil {

    /**
     * 通过反射方式获取主APP的BuildConfig值
     */
    fun getBuildConfigValue(packageName: String, fieldName: String = "DEBUG"): Any? {
        try {
            val clazz = Class.forName("$packageName.BuildConfig")
            val field = clazz.getField(fieldName)
            return field.get(null)
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        return null
    }

    fun startDownloadService(context: Context, downloadTitle: String?, downloadUrl: String, mListener: DownloadServiceListener) {
        // 判读版本是否在8.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 判断应用是否有权限安装apk
            // 会出现bug: Need to declare android.permission.REQUEST_INSTALL_PACKAGES to call this api
            val installAllowed = context.packageManager.canRequestPackageInstalls()

            if (installAllowed) {
                startDownloadOnPermission(context, downloadTitle, downloadUrl, mListener)
            } else {
                // 请求权限
                val permissionManager = ManagerFactory.getManagerService(PermissionManager::class.java)
                if (!permissionManager.hasPermissions(context, Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
                    permissionManager.requestPermissions(context, object : PermissionManager.PermissionListener {
                        override fun onPermissionsGranted(perms: List<String>) {
                            startDownloadOnPermission(context, downloadTitle, downloadUrl, mListener)
                        }

                        override fun onPermissionsDenied(perms: List<String>) {
                            ModalManager.BmToast.toast(context, "请先允许安装未知来源的应用程序", Toast.LENGTH_SHORT)
                            val uri = Uri.parse("package:" + context.packageName)
                            val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, uri)
                            (context as Activity).startActivityForResult(intent, REQUEST_CODE_APP_INSTALL)
                        }

                        override fun onPermissionRequestRejected() {
                            ModalManager.BmToast.toast(context, "拒绝相关权限，更新无法进行！", Toast.LENGTH_SHORT)
                        }
                    },
                        Manifest.permission.REQUEST_INSTALL_PACKAGES
                    )
                } else {
                    startDownloadOnPermission(context, downloadTitle, downloadUrl, mListener)
                }
            }

        } else {
            startDownloadOnPermission(context, downloadTitle, downloadUrl, mListener)
        }
    }

    private fun startDownloadOnPermission(context: Context, downloadTitle: String? = "下载中", downloadUrl: String, mListener: DownloadServiceListener) {
        val mServiceConnection = object : ServiceConnection {
            override fun onServiceDisconnected(name: ComponentName?) {
                mListener.onServiceDisconnected(name)
            }

            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                when (service) {
                    null -> mListener.onError()
                    else -> {
                        val mService = service as ServiceDownload.DownloadBinder
                        if (!mService.serviceIsDownloading()) {
                            mService.start()
                        }
                        mListener.onServiceConnected(name)
                    }
                }
            }
        }

        val intent = Intent(context, ServiceDownload::class.java)
        intent.putExtra(ServiceDownload.BUNDLE_KEY_DOWNLOAD_URL, downloadUrl)
        intent.putExtra(ServiceDownload.BUNDLE_KEY_TITLE, downloadTitle)
        context.startService(intent)
        context.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
    }
}
